using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour
{
    private static GameManager instance;
    public static GameManager Instance
    {
        get
        {
            if (instance == null)
                instance = GameObject.Find("Game Manager").GetComponent<GameManager>();

            return instance;
        }
    }

    public SceneFader sceneFader;
    public List<Orb> orbs;
    public Door door1;

    private float gameTime = 0;
    private bool gameOver = false;

    private void Awake()
    {
        if (instance != null)
        {
            Destroy(gameObject);
            return;
        }

        orbs = new List<Orb>();

        DontDestroyOnLoad(this);
    }

    private void Start()
    {

    }

    private void Update()
    {
        if (gameOver == true)
            return;
        gameTime += Time.deltaTime;
        UIManager.Instance.UpdateGameTimeUI(gameTime);
    }

    private int deathNum = 0;
    public void PlayerDeath()
    {
        sceneFader.FadeOut();
        deathNum++;
        UIManager.Instance.UpdateDeathUI(deathNum);
        Invoke("RestartScene", 1.5f);
    }
    public void PlayerWin()
    {
        gameOver = true;
        UIManager.Instance.DisplyGameOver();
    }
    public void RegisterSceneFader(SceneFader fader)
    {
        sceneFader = fader;
    }
    public void RegisterOrb(Orb orb)
    {
        if (!orbs.Contains(orb))
            orbs.Add(orb);
        UIManager.Instance.UpdateOrbUI(orbs.Count);
    }
    public void RegisterDoor(Door door)
    {
        door1 = door;
    }


    public void PlayerGrabOrb(Orb orb)
    {
        if (!orbs.Contains(orb))
            return;
        orbs.Remove(orb);

        UIManager.Instance.UpdateOrbUI(orbs.Count);
        if (orbs.Count == 0)
        {
            door1.Open();
        }
    }

    private void RestartScene()
    {
        orbs.Clear();
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    }
}
